package com.example.cc.mygit.base;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.app.FragmentTransaction;
import android.view.ViewGroup;

/**
 * Created by cc on 2016/12/3.
 */

public abstract class FragmentAdapter extends FragmentStatePagerAdapter{

    private final FragmentManager mFragmentManager;
    private boolean mUpdateFlag;

    public FragmentAdapter(FragmentManager fm) {
        super(fm);
        this.mFragmentManager = fm;
    }
    public boolean isUpdateFlag(){
        return mUpdateFlag;
    }
    public void setUpdateFlag(boolean mUpdateFlag){
        this.mUpdateFlag = mUpdateFlag;

    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        if (mUpdateFlag){
            Fragment fragment = (Fragment)super.instantiateItem(container,position);
            String tag = fragment.getTag();
            FragmentTransaction transaction = mFragmentManager.beginTransaction();
            transaction.remove(fragment);
            fragment = getItem(position);
            if (!fragment.isAdded()){
                transaction.add(container.getId(),fragment,tag)
                        .attach(fragment)
                        .commitAllowingStateLoss();
            }
            return fragment;
        }
        return super.instantiateItem(container, position);
    }
}
